package com.demo.config;

import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	/**
	 * 设置参数
	 */
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		postProcessBeforeOnStartup(servletContext);
		super.onStartup(servletContext);
		postProcessAfterOnStartup(servletContext);
	}

	/**
	 * 配置过滤器
	 */
	@Override
	protected Filter[] getServletFilters() {
		CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
		characterEncodingFilter.setEncoding("UTF-8");
		characterEncodingFilter.setForceEncoding(true);
		return new Filter[] { characterEncodingFilter };
	}

	/**
	 * 配置
	 */
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { AppConfigMain.class, AppConfigMybatis.class };
	}

	/**
	 * 配置 WebMvcConfigurer
	 */
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[] { WebMvcConfigurer.class };
	}

	/**
	 * 配置 DispatcherServlet Mapping
	 */
	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}

	private void postProcessAfterOnStartup(ServletContext servletContext) {
		// 注册监听器
		servletContext.addListener(RequestContextListener.class);
	}

	private void postProcessBeforeOnStartup(ServletContext servletContext) {
		// 设置参数
		servletContext.setInitParameter("log4jConfigLocation", "classpath:log4j.properties");
		servletContext.setInitParameter("log4jRefreshInterval", "60000");
	}
}
